<!--二维码 管理-->
<template>
  <div id="thirdWechatQrcode" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <application-key-select v-model="listQuery.appId" :type="listQuery.type" @change="handleKeySelectChange" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="listQuery.keyword" placeholder="请输入关键字" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
          <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="标题" prop="title" min-width="200" sortable show-overflow-tooltip />
        <el-table-column label="二维码类型" prop="type" min-width="100" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.type===0" class="color-danger">临时二维码</span>
            <span v-if="scope.row.type===1" class="color-primary">永久二维码</span>
          </template>
        </el-table-column>
        <el-table-column label="消息类型" prop="articleType" min-width="100" sortable>
          <template slot-scope="scope">
            {{ (messageTypes.filter(item=>item.value ===scope.row.articleType ))[0].label }}
          </template>
        </el-table-column>
        <el-table-column label="超时时间(s)" prop="expireSeconds" width="130" sortable show-overflow-tooltip />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="iconQrcode" icon-type="svg" skin="primary" title="二维码" @click="handleQrcode(scope.row)" />
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="thirdWechatQrcodeRules"
          :model="thirdWechatQrcodeRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="AppId:" prop="appId">
            <el-input v-model="thirdWechatQrcodeRecord.appId" disabled show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="标题:" prop="title">
            <el-input v-model="thirdWechatQrcodeRecord.title" maxlength="300" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="类型:" prop="type">
            <el-radio-group v-model="thirdWechatQrcodeRecord.type">
              <el-radio :label="0">临时二维码</el-radio>
              <el-radio :label="1">永久二维码</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="thirdWechatQrcodeRecord.type===0">
            <el-form-item label="超时时间(秒):" prop="expireSeconds">
              <el-input v-model="thirdWechatQrcodeRecord.expireSeconds" maxlength="7" show-word-limit placeholder="请输入超时时间，最大值2592000" />
              <el-radio-group v-model="thirdWechatQrcodeRecord.expireSecondTemp">
                <el-radio :label="0">1小时</el-radio>
                <el-radio :label="1">1天</el-radio>
                <el-radio :label="2">7天</el-radio>
                <el-radio :label="3">30天</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>

          <el-form-item label="消息类型" prop="article">
            <el-input v-model="thirdWechatQrcodeRecord.article" maxlength="20" show-word-limit placeholder="请输入" />
          </el-form-item>

        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>

    <model-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="350px"
      :show-close="false"
      @close="dialogVisible=!dialogVisible">
      <div
        ref="wechatQrcode"
        v-loading="wechatQrCodeLoading"
        class="wechat-qrcode-container"
        element-loading-text="场景码下载导出中...">
        <div class="wechat-title">{{ selectedWechat.name }}</div>
        <div class="wechat-qrcode"><img :src="wechatQrCode"></div>
        <div class="title">{{ thirdWechatQrcodeRecord.title }}</div>
        <div class="desc">
          <template v-if="thirdWechatQrcodeRecord.type===0">
            临时二维码<br>
            有效期至:{{ (new Date().getTime()+thirdWechatQrcodeRecord.expireSeconds*1000) | formatDate('yyyy-MM-dd hh:mm:ss') }}({{ thirdWechatQrcodeRecord.expireSeconds*1000 | formatRunTime }})
          </template>
          <span v-if="thirdWechatQrcodeRecord.type===1">永久二维码</span>
        </div>
      </div>
      <template slot="footer">
        <el-button type="primary" plain @click="handleDownload">下 载</el-button>
      </template>
    </model-dialog>
  </div>
</template>

<script>
import applicationKeySelect from '../applicationKeySelect'
import html2canvas from 'html2canvas'
export default {
  components: { applicationKeySelect },

  data() {
    return {
      selectedWechat: {},
      list: [],
      total: 0,
      listQuery: {
        appId: '',
        type: 1,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },
      messageTypes: [
        { label: '文本', value: 0 },
        { label: '语音', value: 1 },
        { label: '视频', value: 2 },
        { label: '图片', value: 3 },
        { label: '图文', value: 4 }
      ],

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      thirdWechatQrcodeRecord: {},
      thirdWechatQrcodeRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        expireSeconds: [
          { required: true, message: '请输入超时时间', trigger: 'blur' },
          { validator: this.commonValidate.validateNumber, trigger: 'blur' }
        ],
        article: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]

      },
      dialogVisible: false,
      dialogTitle: '场景二维码',
      wechatQrCode: null,
      wechatQrCodeLoading: false
    }
  },
  watch: {
    'thirdWechatQrcodeRecord.expireSecondTemp': function(val) {
      var expireSeconds = -1
      if (val === 0) {
        expireSeconds = 1 * 60 * 60
      }
      if (val === 1) {
        expireSeconds = 1 * 24 * 60 * 60
      }
      if (val === 2) {
        expireSeconds = 7 * 24 * 60 * 60
      }
      if (val === 3) {
        expireSeconds = 30 * 24 * 60 * 60
      }
      this.thirdWechatQrcodeRecord = {
        ...this.thirdWechatQrcodeRecord,
        expireSeconds: expireSeconds
      }
    },
    'listQuery.appId': function(val) {
      this.fetchData()
    }
  },
  created() {
  },
  methods: {
    handleKeySelectChange(val) {
      this.selectedWechat = val
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('thirdWechatQrcodePage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.thirdWechatQrcodeRecord = {
        appId: this.listQuery.appId,
        type: 0,
        articleType: 0
      }
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增二维码 '
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('thirdWechatQrcodeSave', this.thirdWechatQrcodeRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.thirdWechatQrcodeRecord = Object.assign({}, row) // copy obj
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑二维码 '
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.thirdWechatQrcodeRecord)
          this.$store.dispatch('thirdWechatQrcodeUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('thirdWechatQrcodeRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },
    handleQrcode(row) {
      this.wechatQrCodeLoading = false
      this.thirdWechatQrcodeRecord = row
      this.dialogVisible = true
      this.dialogTitle = `【${row.title}】场景二维码`
      this.$store.dispatch('generateWechatQrCode', { id: row.id, appId: row.appId }).then((res) => {
        this.wechatQrCode = res
      }).catch((err) => {
        console.log(err)
      })
    },
    handleDownload() {
      this.wechatQrCodeLoading = true
      html2canvas(this.$refs.wechatQrcode, {}).then(canvas => {
        const dataURL = canvas.toDataURL('image/png')
        if (dataURL !== '') {
          var a = document.createElement('a')
          a.download = `【${this.thirdWechatQrcodeRecord.title}】场景码.jpg`
          a.href = dataURL
          a.click()
        }
        this.wechatQrCodeLoading = false
      })
    }

  }
}
</script>
<style lang="scss" scoped>
  .wechat-qrcode-container{
    text-align: center;
    padding: 20px;
    background: #07c260;
    border-radius: 8px;
    .wechat-title{
      font-size: 20px;
      font-weight: bolder;
      margin-bottom: 10px;
      color: #fff;
    }
    .wechat-qrcode{
      width: 200px;
      height: 200px;
      margin: 0 auto;
      border: 1px solid #fff;
      border-radius: 4px;
      img{
        width: 100%;
        height: 100%;
      }
    }
    .title{
      font-size: 16px;
      font-weight: bolder;
      margin-bottom: 10px;
      margin-top: 10px;
      color: #fff;
    }
    .desc{
      color: #fff;
      font-size: 13px;
    }
  }
</style>
